<!-- 模板 -->
<template>
    <div>
      <el-tree ref="treeRef" node-key="id" :data="tree" :show-checkbox = "isCheckBox" :props="defaultProps" :default-expand-all="true" :highlight-current = "true" :expand-on-click-node = "false" @node-click="handleNodeClick"  />
    </div>
  </template>

  <script lang="ts">
  import router from '@/router'
  import { moduleExpression } from '@babel/types'
  import menuEnums from '@/config/Enums/menu'
  import Pinterface from '@/config/Interface/Public'
  import Interface from '@/config/Interface/Menu'
  import { defineComponent,ref,onMounted,reactive,toRefs, onBeforeUnmount} from 'vue'
  import { getCurrentInstance} from 'vue'
  import { useStore } from '../../store'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  import {createUserApi,updateUserApi} from '@/request/user'
  import menuTree from '@/components/menu/menuTree.vue'
  export default defineComponent({
    name: 'chooseMenu',
    components: {

    },
    props: { 
      isCheckBox:Boolean,
     },
    setup(props,{ emit }){
      const store = useStore()

      const context = getCurrentInstance()?.appContext.config.globalProperties; //获取this
      const msg = reactive<any>({})
      const model =ref(false) // 模态框显示隐藏
      const type = ref('') //类型 添加/编辑
      const {isCheckBox} = toRefs(props)
      const treeRef = ref()
      const reactiveData = reactive({
        tree : [{
          id:0,
          label:'资源菜单',
          children:[]
        }]
      })

      let treeData:any = []
      if(store){
         treeData = store.state.userModule.menuTree
      }

      // 处理树形结构
      const mapTree = (org:any) => {
        const haveChildren:any = Array.isArray(org.children) && org.children.length > 0;
        return {
          label: org.title,
          children:haveChildren ? org.children.map((i:any) => mapTree(i)) : [],
          id:org.id
        }
      };
      // 树组件默认配置
      const defaultProps = {
        children: 'children',
        label: 'label',
      }

      const treeDataMap = treeData.map((org :any) => mapTree(org) )

      const handleNodeClick = async (data:any) => {
        emit('handleNodeClickEmit',data,treeData)
      }

      interface Tree {
        name: string
      } 

      const getSelectedTreeKey = ():number[]=>{
        return treeRef.value!.getCheckedKeys(false)
      }

      onMounted(()=>{
         reactiveData.tree[0].children = treeDataMap
      })

      const setChanged = (keys:any)=>{
        treeRef.value!.setCheckedKeys(keys,false)
      }

      const clear = () =>{
        treeRef.value!.setCheckedKeys([],false)
      }
      


      return {
        ...toRefs(reactiveData),
        handleNodeClick,defaultProps,
        isCheckBox,treeRef,clear,setChanged,getSelectedTreeKey
      }
    }
  })
  </script>

  <style scoped lang="stylus">
  </style>
